-
Notifications
You must be signed in to change notification settings - Fork 4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add logging #143
Add logging #143
Conversation
WalkthroughThis pull request introduces several enhancements across multiple packages, primarily focusing on integrating the Changes
Assessment against linked issues
Possibly related PRs
Suggested reviewers
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 10
🧹 Outside diff range and nitpick comments (46)
packages/ciphernode/test_helpers/Cargo.toml (1)
16-16
: LGTM! Consider adding features for tracing.The addition of the
tracing
dependency is appropriate and aligns with the PR objectives to enhance logging capabilities. This change will allow the use of structured logging in the test helpers, which can significantly improve debugging and observability during testing.Consider specifying any specific features of the
tracing
crate that you intend to use. For example, if you plan to use thelog
compatibility layer, you could modify the dependency like this:tracing = { workspace = true, features = ["log"] }This can help to explicitly document which features of
tracing
are being used in the test helpers.packages/ciphernode/sortition/Cargo.toml (1)
18-18
: LGTM! Consider specifying features fortracing
.The addition of the
tracing
crate as a workspace dependency is a good step towards improving logging capabilities, which aligns well with the PR objectives. This change will enable structured, contextual, and async-aware logging in the sortition package.Consider specifying the features you intend to use from the
tracing
crate. This can help optimize compile times and binary size. For example:tracing = { workspace = true, features = ["attributes"] }Replace
["attributes"]
with the specific features you need. If you're unsure which features to include, you can leave it as is for now and optimize later when you have a better understanding of your logging requirements.packages/ciphernode/enclave/Cargo.toml (1)
17-18
: LGTM! Consider adding version constraints.The addition of
tracing
andtracing-subscriber
dependencies aligns well with the PR objectives to enhance logging functionality. Usingworkspace = true
ensures consistent versioning across the workspace, which is a good practice.Consider adding version constraints to these dependencies in the workspace Cargo.toml file if they're not already present. This helps ensure reproducible builds and easier upgrades in the future.
packages/ciphernode/test_helpers/src/utils.rs (2)
12-15
: LGTM: Good addition of structured logging with error handling.The match statement effectively logs the path being written to and handles the case where the path can't be converted to a string. The use of
trace!
for successful cases anderror!
for failures is appropriate.Consider using a consistent style for the
path
field in both arms of the match:match abs_path.to_str() { Some(s) => trace!(path = s, "Writing to path"), - None => error!(path=?abs_path, "Cannot parse path"), + None => error!(path = ?abs_path, "Cannot parse path"), }This change adds a space after
=
in theNone
arm, matching the style in theSome
arm.
Line range hint
1-28
: Overall: Excellent implementation of structured logging.The changes in this file successfully implement the PR objective of replacing
println
withtracing::xxxx()
logging methods. The additions enhance the logging capabilities of thewrite_file_with_dirs
function without altering its core functionality. These improvements will significantly aid in debugging and monitoring.Key improvements:
- Added appropriate imports for tracing.
- Implemented structured logging for the file path being written.
- Added error logging for cases where the path can't be parsed.
- Replaced
println!
withtrace!
for successful file writes.The suggested minor improvements (consistent formatting and safer path handling) will further enhance the robustness of the logging implementation.
Consider applying similar logging improvements consistently across the codebase to maintain a uniform approach to logging and error handling.
packages/ciphernode/enclave/src/bin/aggregator.rs (2)
22-22
: LGTM with suggestions: Tracing subscriber initializedThe tracing subscriber is correctly initialized, which is necessary for the tracing macros to function. However, consider the following suggestions:
- Configure log levels, possibly based on environment (e.g., debug level for development, info for production).
- Consider allowing configuration of output destinations (e.g., stdout, file) based on runtime parameters.
Example:
let subscriber = tracing_subscriber::FmtSubscriber::builder() .with_max_level(tracing::Level::INFO) .finish(); tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
Line range hint
1-33
: Summary: Tracing successfully implementedThe changes in this file successfully implement the tracing crate for improved logging:
- The necessary import for
tracing::info
has been added.- The tracing subscriber is initialized, enabling the use of tracing macros.
- The
println!
macro has been replaced with theinfo!
macro from tracing.These changes align well with the PR objectives and enhance the logging capabilities of the application. Consider the earlier suggestion about configuring log levels and output destinations for even more flexibility.
To further improve the logging architecture:
- Consider creating a separate logging module to centralize logging configuration.
- Implement different log levels (debug, warn, error) throughout the application for more granular logging.
- Add context to log messages where appropriate, such as including relevant variable values or system state.
packages/ciphernode/test_helpers/src/public_key_writer.rs (2)
32-32
: LGTM: Improved logging with structured format.The replacement of
println!
withinfo!
enhances the logging mechanism by using structured logging. This change aligns well with the PR objectives and improves the overall logging quality.Consider adding more context to the log message:
info!(path = &self.path, "Writing aggregated public key to file");This provides slightly more information about what type of public key is being written.
Line range hint
1-34
: Overall: Good improvement in logging, consider extending throughout the file.The changes successfully implement structured logging using the
tracing
crate, which aligns with the PR objectives. This improves log quality and parseability without affecting the core functionality of thePublicKeyWriter
.For consistency, consider updating other potential logging statements in this file (if any) to use the
tracing
crate. Also, it might be beneficial to add debug-level logging for other significant operations in thePublicKeyWriter
, such as when it's attached to the event bus.Example:
pub fn attach(path: &str, bus: Addr<EventBus>) -> Addr<Self> { let addr = Self { path: path.to_owned(), } .start(); bus.do_send(Subscribe { listener: addr.clone().recipient(), event_type: "PublicKeyAggregated".to_string(), }); debug!(path = path, "PublicKeyWriter attached to event bus"); addr }This would provide a more comprehensive logging coverage for the
PublicKeyWriter
operations.packages/ciphernode/test_helpers/src/plaintext_writer.rs (1)
34-34
: LGTM: Improved logging with structured fields.The replacement of
println!
withinfo!
successfully implements the PR's objective. The use of a structured field (path
) enhances the log's informativeness, making it easier to filter and analyze logs.A minor suggestion for improvement:
Consider adding the
output.len()
to the log message to provide more context. This could be helpful for debugging or monitoring purposes. Here's a suggested modification:info!(path = &self.path, output_length = output.len(), "Writing Plaintext To Path");packages/ciphernode/enclave/src/main.rs (2)
33-33
: LGTM: Tracing subscriber initialized, consider error handlingThe initialization of the tracing subscriber is correctly placed at the beginning of the main function. This sets up the logging infrastructure as intended.
Consider adding error handling for the initialization:
tracing_subscriber::fmt::init().expect("Failed to initialize tracing");This will provide more informative feedback if the initialization fails.
38-38
: LGTM: Println replaced with info! macroThe replacement of
println!
withinfo!
for logging the ciphernode launch is correct and aligns with the PR objective. This change enhances logging by using structured logging.For consistency with typical log messages, consider changing the log message to lowercase:
info!("Launching ciphernode: ({})", address);This follows common logging conventions where only the first letter is capitalized.
packages/ciphernode/router/src/ciphernode_selector.rs (2)
55-55
: Consider usinginto()
instead ofclone()
.The change to clone
address
when passing it toGetHasNode
is good for ownership. However, for a small optimization, consider usingaddress.into()
instead ofaddress.clone()
. This allows for a potentially more efficient conversion ifaddress
is already owned.- address: address.clone(), + address: address.into(),
61-61
: LGTM: Informative log message added.The addition of this log message aligns well with the PR objective of enhancing logging functionality. It provides valuable information about ciphernode selection, which can aid in debugging and monitoring.
Consider adding more context to the log message:
- info!(node = address, "Ciphernode was not selected"); + info!(node = address, seed = seed, size = size, "Ciphernode was not selected for committee");This change would provide more context about the selection process, including the seed and committee size.
packages/ciphernode/evm/src/helpers.rs (1)
35-41
: LGTM: Logging statements added effectivelyThe new logging statements enhance the observability of the
stream_from_evm
function without altering its core functionality. They provide valuable insights into the log processing flow.Suggestion for improvement:
Consider adding more context to the log messages. For example:-trace!("Received log from EVM"); +trace!("Received log from EVM: {:?}", log); -trace!("Failed to extract log from EVM"); +trace!("Failed to extract log from EVM: {:?}", log); -info!("Extracted log from evm sending now."); +info!("Extracted log from EVM, sending event: {:?}", event);This additional context could be valuable for debugging and monitoring.
packages/ciphernode/evm/src/enclave_sol_writer.rs (1)
97-97
: Approved: Improved logging with structured formatThe replacement of
println!
withinfo!
and the use of a structured logging format is a significant improvement. This change aligns perfectly with the PR objective and enhances the logging mechanism.Consider adding a more descriptive message to provide context:
-info!(tx=%receipt.transaction_hash, "tx") +info!(tx=%receipt.transaction_hash, "Transaction published successfully")This change would make the log message more informative and easier to understand at a glance.
packages/ciphernode/evm/src/registry_filter_sol.rs (1)
96-96
: Approved: Enhanced logging with tracingThe replacement of
println!
withinfo!
from thetracing
crate is a good improvement. It provides structured logging, which is more suitable for production environments and easier to parse programmatically.A minor suggestion to improve clarity:
Consider adding a more descriptive message to the log. For example:
info!(tx=%receipt.transaction_hash, "Committee published successfully");This provides more context about what the transaction represents.
packages/ciphernode/router/src/hooks.rs (3)
40-42
: LGTM: Improved error handling for LazyKeyshareThe addition of error handling for the missing
fhe
instance is a good improvement. It provides clear feedback when key generation cannot proceed due to missing dependencies.Consider extracting the error message to a constant for easier maintenance and potential reuse:
const ERR_MSG_FHE_NOT_SET: &str = "Could not create Keyshare because the fhe instance it depends on was not set on the context."; // Then use it in the error reporting: bus.err(EnclaveErrorType::KeyGeneration, anyhow!(ERR_MSG_FHE_NOT_SET));
59-64
: LGTM: Enhanced error handling for LazyPlaintextAggregatorThe addition of error handling for missing
fhe
andmeta
instances is a good improvement. It provides clear feedback when plaintext aggregation cannot proceed due to missing dependencies.For consistency with the previous suggestion, consider extracting the error messages to constants:
const ERR_MSG_FHE_NOT_SET_PLAINTEXT: &str = "Could not create PlaintextAggregator because the fhe instance it depends on was not set on the context."; const ERR_MSG_META_NOT_SET_PLAINTEXT: &str = "Could not create PlaintextAggregator because the meta instance it depends on was not set on the context."; // Then use them in the error reporting: bus.err(EnclaveErrorType::PlaintextAggregation, anyhow!(ERR_MSG_FHE_NOT_SET_PLAINTEXT)); bus.err(EnclaveErrorType::PlaintextAggregation, anyhow!(ERR_MSG_META_NOT_SET_PLAINTEXT));
94-99
: LGTM: Improved error handling for LazyPublicKeyAggregatorThe addition of error handling for missing
fhe
andmeta
instances is a good improvement. It provides clear feedback when public key aggregation cannot proceed due to missing dependencies.For consistency with the previous suggestions, consider extracting the error messages to constants:
const ERR_MSG_FHE_NOT_SET_PUBLICKEY: &str = "Could not create PublicKeyAggregator because the fhe instance it depends on was not set on the context."; const ERR_MSG_META_NOT_SET_PUBLICKEY: &str = "Could not create PublicKeyAggregator because the meta instance it depends on was not set on the context."; // Then use them in the error reporting: bus.err(EnclaveErrorType::PublickeyAggregation, anyhow!(ERR_MSG_FHE_NOT_SET_PUBLICKEY)); bus.err(EnclaveErrorType::PublickeyAggregation, anyhow!(ERR_MSG_META_NOT_SET_PUBLICKEY));Consider refactoring the error checking logic for
fhe
andmeta
instances into a separate function to reduce code duplication betweenLazyPlaintextAggregator::create
andLazyPublicKeyAggregator::create
. For example:fn check_dependencies(ctx: &Context, bus: &Addr<EventBus>, error_type: EnclaveErrorType) -> Result<(), ()> { if ctx.fhe.is_none() { bus.err(error_type, anyhow!("Could not create aggregator because the fhe instance it depends on was not set on the context.")); return Err(()); } if ctx.meta.is_none() { bus.err(error_type, anyhow!("Could not create aggregator because the meta instance it depends on was not set on the context.")); return Err(()); } Ok(()) } // Then use it in both create methods: if check_dependencies(ctx, &bus, EnclaveErrorType::PlaintextAggregation).is_err() { return; }This refactoring would make the code more maintainable and reduce the risk of inconsistencies between similar error handling blocks.
packages/ciphernode/evm/src/enclave_sol_reader.rs (2)
59-61
: Enhance error message for E3Requested parsingThe use of
error!
macro is appropriate for logging parsing errors. However, consider enhancing the error message to provide more context:- error!("Error parsing event E3Requested after topic matched!"); + error!("Failed to parse E3Requested event: {:?}", data);This change would log the actual data that failed to parse, aiding in debugging efforts.
72-76
: LGTM: Trace logging for unknown events (with minor typo)The addition of
trace!
logging for unknown events is a good practice. It provides visibility into unexpected events without cluttering logs at higher severity levels.There's a small typo in the log message:
- "Unknown event was received by Enclave.sol parser buut was ignored" + "Unknown event was received by Enclave.sol parser but was ignored"packages/ciphernode/evm/src/ciphernode_registry_sol.rs (4)
11-11
: LGTM! Consider grouping related imports.The addition of the
tracing
crate import aligns well with the PR objective of enhancing logging functionality. The specific macros imported (error
,info
,trace
) suggest a structured approach to logging at different levels, which is a good practice.Consider grouping related imports together. You could move this import closer to other external crate imports for better organization.
73-75
: LGTM! Consider adding more context to the error log.The replacement of
println!
with theerror!
macro fromtracing
is a good improvement, aligning with the PR objectives. This change enhances the logging structure and will likely improve error tracking and debugging.Consider adding more context to the error log, such as including the
data
that failed to parse. This could help with debugging in the future. For example:error!("Error parsing event CiphernodeAdded after topic was matched. Data: {:?}", data);
81-83
: LGTM! Consider adding more context to the error log.The replacement of
println!
with theerror!
macro fromtracing
is consistent with the previous change and aligns well with the PR objectives. This change contributes to a more structured and effective logging system.Similar to the previous suggestion, consider adding more context to the error log by including the
data
that failed to parse. For example:error!("Error parsing event CiphernodeRemoved after topic was matched. Data: {:?}", data);
87-91
: LGTM! Minor typo in the log message.The addition of the
trace!
macro for logging unknown events is a good improvement. It enhances the traceability of event handling without cluttering logs with potentially frequent occurrences of unknown events. The use oftrace!
level is appropriate for this kind of information.There's a minor typo in the log message. "buut" should be "but":
trace!( topic=?_topic, "Unknown event was received by Enclave.sol parser but was ignored" );tests/basic_integration/test.sh (2)
15-15
: LGTM! Consider making the log level configurable.The addition of
export RUST_LOG=info
aligns well with the PR objectives of enhancing logging functionality. This will enable more detailed logging for Rust components during test execution.To improve flexibility, consider making the log level configurable:
-export RUST_LOG=info +export RUST_LOG=${RUST_LOG:-info}This change allows overriding the log level when running the script, while maintaining "info" as the default.
Line range hint
1-168
: Consider adding bash logging statements for improved debugging.While the
RUST_LOG
environment variable has been set for Rust components, adding some bash logging statements throughout this script could further enhance debugging capabilities during integration testing.Here's an example of how you could add logging to key sections of the script:
log_info() { echo "[INFO] $(date '+%Y-%m-%d %H:%M:%S') - $1" } # Add this function near the top of the script # Then use it throughout the script, for example: log_info "Starting EVM node" yarn evm:node & log_info "Launching ciphernode $CIPHERNODE_ADDRESS_1" yarn ciphernode:launch --address $CIPHERNODE_ADDRESS_1 --config "$SCRIPT_DIR/lib/ciphernode_config.yaml" & # ... and so on for other key operationsThis will provide a consistent logging format for bash operations, complementing the Rust logging.
🧰 Tools
🪛 Shellcheck
[warning] 18-18: RPC_URL appears unused. Verify use (or export if used externally).
(SC2034)
packages/ciphernode/aggregator/src/plaintext_aggregator.rs (3)
128-128
: LGTM: Replaced println! with structured loggingThe changes successfully replace
println!
statements witherror!
macros from thetracing
crate, aligning with the PR objectives. This enhances the logging mechanism by providing structured logs instead of simple console output.Minor suggestion: Consider adding more context to the error messages, such as including the
e3_id
in the log when the wrong ID is sent to the aggregator. This could further improve debuggability.Example:
error!(?e3_id, expected_e3_id = ?act.e3_id, "Wrong e3_id sent to aggregator. This should not happen.");Also applies to: 148-148, 153-153
Line range hint
64-64
: LGTM: Improvedadd_share
method return typeThe change to return
Result<PlaintextAggregatorState>
instead ofResult<()>
is a good improvement. It provides more information about the aggregator's state after adding a share, allowing callers to react to state changes more effectively.Suggestion: Consider using the
?
operator for error propagation instead of early returns. This can make the code more concise and consistent with Rust's error handling patterns.Example:
pub fn add_share(&mut self, share: Vec<u8>) -> Result<PlaintextAggregatorState> { let PlaintextAggregatorState::Collecting { threshold_m, shares, ciphertext_output, .. } = &mut self.state else { return Err(anyhow::anyhow!("Can only add share in Collecting state")); }; shares.insert(share); Ok(if shares.len() == *threshold_m { PlaintextAggregatorState::Computing { shares: shares.clone(), ciphertext_output: ciphertext_output.to_vec(), } } else { self.state.clone() }) }Also applies to: 65-65, 66-66, 67-67, 68-68, 69-69, 70-70, 71-71, 72-72, 73-73, 74-74, 75-75, 76-76, 77-77, 78-78, 79-79, 80-80, 81-81, 82-82, 83-83, 84-84
Line range hint
86-86
: LGTM: Improvedset_decryption
method return typeThe change to return
Result<PlaintextAggregatorState>
instead ofResult<()>
is consistent with the improvements made to theadd_share
method. This provides better visibility into the aggregator's state after setting the decryption.Suggestion: For consistency with the
add_share
method, consider handling the case where the state is notComputing
more explicitly:pub fn set_decryption(&mut self, decrypted: Vec<u8>) -> Result<PlaintextAggregatorState> { let PlaintextAggregatorState::Computing { shares, .. } = &mut self.state else { return Err(anyhow::anyhow!("Can only set decryption in Computing state")); }; let shares = shares.to_owned(); Ok(PlaintextAggregatorState::Complete { decrypted, shares }) }This change would make the error handling more explicit and consistent across both methods.
Also applies to: 87-87, 88-88, 89-89, 90-90, 91-91, 92-92, 93-93, 94-94, 95-95
packages/ciphernode/aggregator/src/publickey_aggregator.rs (4)
136-136
: LGTM: Improved logging with structured formatThe replacement of
println!
witherror!
enhances logging capabilities as intended. The inclusion of the state in the log message provides valuable context.Consider adding a static string identifier to make log filtering easier:
error!(event = "aggregator_closed", state = ?self.state, "Aggregator has been closed for collecting keyshares.");
158-158
: Approved: Logging improved, but could be more informativeThe replacement of
println!
witherror!
is good. However, the log message could be more informative.Consider adding more context:
error!(event = "node_not_in_committee", address = ?address, "Node not found in committee");This addition provides more details about which node was not found, making debugging easier.
163-163
: Approved: Logging improved, but could be more detailedThe switch to
error!
is good. However, for unexpected scenarios like this, more detailed logging would be beneficial.Consider enhancing the log message:
error!( event = "wrong_e3_id", expected_e3_id = ?act.e3_id, received_e3_id = ?e3_id, "Incorrect e3_id sent to aggregator. This indicates a potential bug or security issue." );This provides more context about the mismatch and emphasizes the severity of the situation.
Line range hint
1-238
: Summary: Logging improvements successfully implementedThe changes in this file successfully replace
println!
statements withtracing::error!
calls, aligning with the PR objectives. These improvements enhance the ability to debug and monitor the application by providing structured logging.Consider reviewing the entire file for other locations where similar logging improvements could be applied, especially for important events or error conditions. This would ensure consistency in logging practices throughout the
PublicKeyAggregator
implementation.packages/ciphernode/core/src/events.rs (3)
186-201
: Approve the new get_data method with a minor suggestionThe new
get_data
method provides a consistent way to get a string representation of the event data, which is excellent for logging and debugging purposes. It leverages theDisplay
trait implementations of the inner data structures, promoting code reuse.Consider handling the default case explicitly instead of commenting it out. You could either remove the comment or implement a default case:
pub fn get_data(&self) -> String { match self.clone() { EnclaveEvent::KeyshareCreated { data, .. } => format!("{}", data), EnclaveEvent::E3Requested { data, .. } => format!("{}", data), EnclaveEvent::PublicKeyAggregated { data, .. } => format!("{}", data), EnclaveEvent::CiphertextOutputPublished { data, .. } => format!("{}", data), EnclaveEvent::DecryptionshareCreated { data, .. } => format!("{}", data), EnclaveEvent::PlaintextAggregated { data, .. } => format!("{}", data), EnclaveEvent::CiphernodeSelected { data, .. } => format!("{}", data), EnclaveEvent::CiphernodeAdded { data, .. } => format!("{}", data), EnclaveEvent::CiphernodeRemoved { data, .. } => format!("{}", data), EnclaveEvent::E3RequestComplete { data, .. } => format!("{}", data), EnclaveEvent::EnclaveError { data, .. } => format!("{:?}", data), - // _ => "<omitted>".to_string(), + _ => "<unknown event>".to_string(), } }This ensures that all possible cases are handled explicitly.
330-334
: Approve new Display implementations with a suggestion for consistencyThe new
Display
implementations for various structs greatly enhance the readability of logs and debug outputs. They provide a consistent format for representing the data of different event types.For consistency, consider using the same format for all structs. Some implementations use
<omitted>
for sensitive or large fields, while others simply exclude them. Standardize this approach across all implementations. For example:impl Display for PublicKeyAggregated { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, - "e3_id: {}, src_chain_id: {}, nodes: <omitted>, pubkey: <omitted>", - self.e3_id, self.src_chain_id, + "e3_id: {}, src_chain_id: {}, nodes: <omitted>, pubkey: <omitted>", + self.e3_id, self.src_chain_id ) } }Apply this consistently to all
Display
implementations where applicable.Also applies to: 344-348, 359-367, 379-386, 396-404, 413-417, 427-435, 444-448, 458-466, 476-484, 493-497, 502-506
376-377
: Approve retention of src_chain_id with a suggestion for documentationThe decision to keep the
src_chain_id
field in theE3Requested
struct has been finalized, as evidenced by the removal of comments indicating potential future modifications.Consider adding a brief documentation comment to explain the purpose and significance of the
src_chain_id
field. This will help future developers understand its role in the E3 request process. For example:pub struct E3Requested { pub e3_id: E3id, pub threshold_m: usize, pub seed: Seed, pub params: Vec<u8>, + /// Identifier of the source chain initiating the E3 request pub src_chain_id: u64, }
packages/ciphernode/sortition/src/sortition.rs (1)
Line range hint
52-53
: Handle parsing errors instead of using.unwrap()
Using
.unwrap()
onb.parse()
can cause the program to panic if the parsing fails. It's better to handle the potential error to make the code more robust.Here's how you can handle the parsing errors:
- // TODO: error handling - .map(|b| b.parse().unwrap()) - .collect(); + .map(|b| { + b.parse().map_err(|e| anyhow!("Failed to parse address {}: {}", b, e)) + }) + .collect::<Result<Vec<_>>>()?;This modification propagates the parsing errors properly, allowing the calling function to handle them as needed.
packages/ciphernode/p2p/src/p2p.rs (3)
12-12
: Correct the typo in the documentation comment.In the documentation comment, 'EVentBus' should be 'EventBus'.
Line range hint
65-72
: Avoid usingunwrap()
inside asynchronous tasks.Using
unwrap()
insidetokio::spawn
can cause the task to panic if an error occurs. To prevent unexpected panics, handle the error explicitly.Apply this diff to handle the potential error:
tokio::spawn(async move { - libp2p.start().await.unwrap() + if let Err(e) = libp2p.start().await { + error!("Error starting libp2p: {:?}", e); + // Consider additional error handling here + } });
105-105
: Consider adjusting the logging level fromtrace!
todebug!
.The
trace!
macro is used for very detailed diagnostic information. If these messages are intended for standard debugging, usingdebug!
may be more appropriate to avoid excessive verbosity in the logs.Also applies to: 111-111
packages/ciphernode/p2p/src/libp2p_router.rs (4)
Line range hint
114-129
: Avoid using.unwrap()
without checking forNone
The method
start
contains multiple instances of.unwrap()
onself.swarm
andself.topic
. Using.unwrap()
can lead to a panic if these options areNone
. It's safer to handle theNone
case explicitly.Consider refactoring to handle
None
values gracefully:pub async fn start(&mut self) -> Result<(), Box<dyn Error + Send + Sync + 'static>> { if let (Some(swarm), Some(topic)) = (self.swarm.as_mut(), self.topic.as_ref()) { swarm.listen_on("/ip4/0.0.0.0/udp/0/quic-v1".parse()?)?; swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?; loop { select! { Some(line) = self.cmd_rx.recv() => { if let Err(e) = swarm.behaviour_mut().gossipsub.publish(topic.clone(), line) { error!(error = ?e, "Error publishing line to swarm"); } } event = swarm.select_next_some() => match event { // ... rest of the event handling ... } } } } else { return Err("Swarm or topic not initialized".into()); } }
Line range hint
136-158
: Consider adjusting log levels for better visibilityCurrently, events like peer discovery and message reception are logged using
trace!
. Depending on your logging strategy, you might want to usedebug!
orinfo!
to make these logs more visible during normal operation.
114-116
: Enhance documentation for thestart
methodThe comment
/// Listen on the default multiaddr
is brief. Expanding the documentation can help other developers understand the method's purpose and usage.Consider updating the documentation:
/// Starts the `EnclaveRouter`, listening on the default multiaddresses and processing incoming commands and swarm events. /// /// This method sets up listeners for both QUIC and TCP transports, /// handles publishing messages received from `cmd_rx`, /// and processes various swarm events such as new peers discovered via mDNS. /// /// # Errors /// /// Returns an error if the swarm fails to listen on the specified addresses or if message handling encounters an issue.
Line range hint
114-129
: Use specific error types instead ofBox<dyn Error>
Returning
Box<dyn Error + Send + Sync + 'static>
erases the concrete error types, making error handling less precise. Consider defining a custom error type or using a specific error enum to improve clarity.Define a custom error enum:
#[derive(Debug, thiserror::Error)] pub enum EnclaveRouterError { #[error("Swarm or topic not initialized")] Uninitialized, #[error("IO error")] Io(#[from] io::Error), #[error("Gossipsub error")] Gossipsub(#[from] gossipsub::error::PublishError), // ... other error variants ... }Update the method signature:
pub async fn start(&mut self) -> Result<(), EnclaveRouterError> { // ... method implementation ... }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
⛔ Files ignored due to path filters (1)
packages/ciphernode/Cargo.lock
is excluded by!**/*.lock
📒 Files selected for processing (30)
- packages/ciphernode/aggregator/Cargo.toml (1 hunks)
- packages/ciphernode/aggregator/src/plaintext_aggregator.rs (3 hunks)
- packages/ciphernode/aggregator/src/publickey_aggregator.rs (3 hunks)
- packages/ciphernode/core/src/events.rs (12 hunks)
- packages/ciphernode/enclave/Cargo.toml (1 hunks)
- packages/ciphernode/enclave/src/bin/aggregator.rs (2 hunks)
- packages/ciphernode/enclave/src/main.rs (2 hunks)
- packages/ciphernode/enclave_node/src/main.rs (0 hunks)
- packages/ciphernode/evm/Cargo.toml (1 hunks)
- packages/ciphernode/evm/src/ciphernode_registry_sol.rs (3 hunks)
- packages/ciphernode/evm/src/enclave_sol_reader.rs (3 hunks)
- packages/ciphernode/evm/src/enclave_sol_writer.rs (2 hunks)
- packages/ciphernode/evm/src/helpers.rs (2 hunks)
- packages/ciphernode/evm/src/registry_filter_sol.rs (2 hunks)
- packages/ciphernode/keyshare/src/keyshare.rs (0 hunks)
- packages/ciphernode/logger/Cargo.toml (1 hunks)
- packages/ciphernode/logger/src/logger.rs (3 hunks)
- packages/ciphernode/p2p/src/libp2p_router.rs (5 hunks)
- packages/ciphernode/p2p/src/p2p.rs (5 hunks)
- packages/ciphernode/router/Cargo.toml (1 hunks)
- packages/ciphernode/router/src/ciphernode_selector.rs (2 hunks)
- packages/ciphernode/router/src/hooks.rs (4 hunks)
- packages/ciphernode/sortition/Cargo.toml (1 hunks)
- packages/ciphernode/sortition/src/sortition.rs (6 hunks)
- packages/ciphernode/test_helpers/Cargo.toml (1 hunks)
- packages/ciphernode/test_helpers/src/plaintext_writer.rs (2 hunks)
- packages/ciphernode/test_helpers/src/public_key_writer.rs (2 hunks)
- packages/ciphernode/test_helpers/src/utils.rs (3 hunks)
- packages/ciphernode/tests/tests/test_aggregation_and_decryption.rs (0 hunks)
- tests/basic_integration/test.sh (1 hunks)
💤 Files with no reviewable changes (3)
- packages/ciphernode/enclave_node/src/main.rs
- packages/ciphernode/keyshare/src/keyshare.rs
- packages/ciphernode/tests/tests/test_aggregation_and_decryption.rs
🧰 Additional context used
🔇 Additional comments (37)
packages/ciphernode/aggregator/Cargo.toml (1)
13-13
: LGTM: Addition oftracing
dependency aligns with PR objectives.The addition of the
tracing
crate as a workspace dependency is consistent with the PR's goal of enhancing logging functionality. This change will enable the use of structured logging in the aggregator package, which can significantly improve debugging and monitoring capabilities.The use of workspace-level version management (
{ workspace = true }
) is also consistent with other dependencies in this file, ensuring proper version coordination across the project.packages/ciphernode/evm/Cargo.toml (1)
15-15
: LGTM: Addition oftracing
crate aligns with PR objectives.The addition of the
tracing
crate as a workspace dependency is appropriate and aligns well with the PR objectives. This change will enable the replacement ofprintln
statements with more structured logging methods provided by thetracing
crate, enhancing the project's logging capabilities.Using
{ workspace = true }
is a good practice as it ensures consistent versioning across the workspace.packages/ciphernode/router/Cargo.toml (1)
14-15
: LGTM! The changes align well with the PR objectives.The addition of
tracing
andanyhow
as dependencies is a positive step towards improving the logging and error handling capabilities of the router package. These changes directly support the PR's goal of enhancing the logging functionality.
tracing
: This addition aligns perfectly with the objective of replacingprintln
with more sophisticated logging methods.anyhow
: While not explicitly mentioned in the PR objectives, this is a valuable addition for improved error handling, which complements well with enhanced logging.Both dependencies are specified to use the workspace version, ensuring consistency across the project.
packages/ciphernode/test_helpers/src/utils.rs (1)
3-3
: LGTM: Tracing import added as per PR objective.The import of
error
andtrace
from thetracing
crate aligns with the PR's goal to enhance logging functionality.packages/ciphernode/enclave/src/bin/aggregator.rs (2)
4-4
: LGTM: Tracing import added correctlyThe import of
tracing::info
is correctly added, which aligns with the PR objective of enhancing logging functionality.
24-24
: LGTM: Println replaced with info loggingThe
println!
macro has been correctly replaced with theinfo!
macro from tracing. This change aligns perfectly with the PR objective and improves the logging mechanism.packages/ciphernode/test_helpers/src/public_key_writer.rs (1)
4-4
: LGTM: Appropriate import for tracing.The addition of
use tracing::info;
is in line with the PR objectives to enhance logging functionality. This import enables the use of structured logging via thetracing
crate.packages/ciphernode/test_helpers/src/plaintext_writer.rs (2)
4-4
: LGTM: Import oftracing::info
aligns with PR objectives.The addition of
use tracing::info;
is in line with the PR's goal to enhance logging functionality. This import enables the use of structured logging, which will improve the application's debugging and monitoring capabilities.
Line range hint
1-42
: Overall: Successful implementation of improved logging.The changes in this file successfully implement the PR objectives by replacing
println!
withtracing::info!
. This enhancement improves the logging capabilities of thePlaintextWriter
struct without altering its core functionality.Please ensure that any tests relying on stdout output (if any) are updated to accommodate this change in logging mechanism. Run the following script to check for any tests that might need updating:
If the script returns any results, please review those test files and update them accordingly.
packages/ciphernode/enclave/src/main.rs (1)
5-5
: LGTM: Tracing import added correctlyThe addition of
use tracing::info;
is appropriate and aligns with the PR objective of enhancing logging functionality.packages/ciphernode/router/src/ciphernode_selector.rs (2)
6-6
: LGTM: Import statement for tracing module.The addition of the
tracing::info
import aligns with the PR objective of enhancing logging functionality. It's correctly placed and properly formatted.
Line range hint
1-72
: Overall assessment: Changes align well with PR objectives.The modifications in this file successfully implement the tracing crate for improved logging, which is consistent with the PR's main objective. The added log message provides valuable information about ciphernode selection, enhancing the debugging and monitoring capabilities of the system.
A few minor suggestions have been made to further optimize the code and improve the logging output. These changes, while not critical, could provide additional benefits in terms of performance and log clarity.
packages/ciphernode/evm/src/helpers.rs (2)
18-18
: LGTM: Tracing import added correctlyThe import of
tracing::{info, trace}
is correctly added and aligns with the PR objective of enhancing logging functionality.
Line range hint
1-124
: Summary: Effective implementation of loggingThe changes in this file successfully implement the PR objective of enhancing logging functionality. The
tracing
crate is correctly imported and used to add strategic log points within thestream_from_evm
function. These additions improve the observability of the EVM log processing without altering the core logic.The log levels are appropriately chosen, with
trace
for detailed debugging andinfo
for significant operational events. This implementation will greatly aid in debugging and monitoring the application's interaction with the EVM.Overall, these changes represent a positive improvement to the codebase.
packages/ciphernode/evm/src/enclave_sol_writer.rs (2)
16-16
: LGTM: New import for structured loggingThe addition of
use tracing::info;
aligns with the PR objective of enhancing logging functionality. This import enables the use of structured logging, which will improve the overall logging mechanism in the codebase.
Line range hint
1-124
: Summary: Successful implementation of structured loggingThe changes in this file successfully implement structured logging using the
tracing
crate, which aligns with the PR objectives. The replacement ofprintln!
withinfo!
and the use of key-value pairs in the log message enhance the logging mechanism, making it more informative and easier to parse.These improvements will facilitate better debugging and monitoring of the application, particularly for transaction-related events. The core functionality of the
EnclaveSolWriter
remains unchanged, ensuring that the existing behavior is preserved while enhancing the logging capabilities.packages/ciphernode/evm/src/registry_filter_sol.rs (2)
15-15
: LGTM: New import for tracingThe addition of
use tracing::info;
is in line with the PR objective to enhance logging functionality. This import will allow the use of structured logging via thetracing
crate.
Line range hint
1-140
: Summary: Successful implementation of tracing for improved loggingThe changes in this file successfully implement the
tracing
crate for improved logging, which aligns with the PR objectives. The modifications include:
- Adding the necessary import for
tracing::info
.- Replacing a
println!
statement with a structured log usinginfo!
.These changes enhance the logging mechanism by providing more structured and easily parseable logs, which is beneficial for debugging and monitoring in production environments. The core functionality of the code remains unchanged, ensuring that this is a non-breaking improvement to the codebase.
Great job on implementing this logging enhancement!
packages/ciphernode/router/src/hooks.rs (2)
4-4
: LGTM: Import changes align with PR objectivesThe addition of
anyhow::anyhow
and the expanded import fromenclave_core
are consistent with the PR's goal of enhancing error handling and logging. These imports provide the necessary tools for implementing the improved error reporting throughout the file.Also applies to: 6-6
Line range hint
1-114
: Overall assessment: Approved with minor suggestionsThe changes in this file successfully implement improved error handling and logging, aligning well with the PR objectives. The modifications consistently enhance the robustness of the code by providing clear error messages when dependencies are missing.
Key improvements:
- Consistent use of
bus.err
for error reporting.- Clear and informative error messages.
- Proper use of
anyhow!
macro for error creation.Suggestions for further improvement:
- Extract error messages to constants for better maintainability.
- Consider refactoring common error checking logic into a separate function to reduce code duplication.
These changes significantly enhance the debugging capabilities of the codebase. Great job on improving the overall quality and maintainability of the code!
packages/ciphernode/evm/src/enclave_sol_reader.rs (3)
10-10
: LGTM: Tracing import added for improved loggingThe addition of the
tracing
crate witherror
,info
, andtrace
macros aligns well with the PR objective of enhancing logging functionality. This change provides a good range of log levels for more structured and informative logging.
112-112
: LGTM: Improved logging in attach methodThe replacement of
println!
withinfo!
and the addition of a structured field for the address is a significant improvement. This change enhances the logging quality and aligns with the PR's objective.
Line range hint
1-134
: Overall assessment: Successful implementation of structured loggingThe changes in this file consistently improve the logging mechanism by replacing
println!
statements with structured logging using thetracing
crate. This aligns perfectly with the PR's objective of enhancing logging functionality.Key improvements:
- Appropriate use of different log levels (error, info, trace).
- Addition of structured fields in log messages for better context.
- Consistent approach to error handling and logging across the file.
These changes will significantly improve debugging and monitoring capabilities in the application. Great job on implementing these improvements!
packages/ciphernode/evm/src/ciphernode_registry_sol.rs (2)
129-129
: LGTM! Good use of structured logging.The replacement of
println!
with theinfo!
macro fromtracing
is a good improvement, consistent with the PR objectives. The use of a structured field for the address (address=%contract_address
) is particularly noteworthy, as it enhances log parsing and filtering capabilities.
Line range hint
1-165
: Overall, excellent improvements to logging functionality.The changes in this file consistently enhance the logging capabilities by replacing
println!
statements with appropriatetracing
macros. This aligns perfectly with the PR objectives and brings several benefits:
- Structured logging: The use of
error!
,info!
, andtrace!
macros provides better structure to the logs.- Log levels: Different log levels allow for more granular control over what gets logged in different environments.
- Improved error context: Error logs now provide clearer context about failures.
- Better traceability: The addition of trace logs for unknown events enhances the overall traceability of the system.
These improvements will significantly aid in debugging and monitoring the application. Great job on implementing these changes consistently throughout the file!
packages/ciphernode/aggregator/src/plaintext_aggregator.rs (1)
10-10
: LGTM: Tracing crate import addedThe addition of
use tracing::error;
aligns with the PR objective of enhancing logging functionality. This import will allow the use of structured logging instead ofprintln!
statements.packages/ciphernode/aggregator/src/publickey_aggregator.rs (1)
9-9
: LGTM: Tracing import added for structured loggingThe addition of
use tracing::error;
is appropriate for implementing structured logging, which aligns with the PR objectives.packages/ciphernode/core/src/events.rs (4)
318-318
: Approve the updated Display implementation for EnclaveEventThe modification to use the new
get_data
method in theDisplay
implementation forEnclaveEvent
is a good improvement. It ensures consistency in how event data is displayed and promotes code reuse.This change aligns well with the new
get_data
method and will provide more informative and consistent log outputs.
Line range hint
1-582
: Overall approval with minor suggestions for improvementThe changes made to this file significantly enhance the logging and debugging capabilities of the enclave system. The addition of
Display
implementations for various structs and the newget_data
method inEnclaveEvent
provide more consistent and informative event representations.Key improvements:
- Enhanced event data representation through new
Display
implementations.- Consistent event data retrieval with the
get_data
method.- Updated
EnclaveErrorType
to includeSortition
errors.Suggestions for further improvement:
- Standardize the approach for omitting sensitive or large fields in
Display
implementations.- Add brief documentation for the
src_chain_id
field in theE3Requested
struct.- Consider explicitly handling the default case in the
get_data
method ofEnclaveEvent
.These changes align well with the PR objective of enhancing logging functionality. The transition from
println
totracing::xxxx()
methods is not directly visible in this file, but these changes support that goal by providing better structured data for logging.
542-542
: Approve addition of Sortition variant with verification suggestionThe addition of the
Sortition
variant to theEnclaveErrorType
enum is approved. This suggests that error handling for sortition-related issues has been introduced in the system.To ensure this new error type is properly handled throughout the codebase, let's verify its usage:
#!/bin/bash # Check for usage of the new Sortition error type rg --type rust 'EnclaveErrorType::Sortition' -C 3This will help us understand where and how the new error type is being used, and if any additional error handling might be needed in other parts of the codebase.
72-72
: Consider the implications of shortening the EventId display formatThe new format "evt:{base58_string[0..8]}" is more concise, which can improve log readability. However, it also reduces the uniqueness of the displayed EventId, potentially making it harder to distinguish between similar events in logs.
To assess the impact of this change, let's check for potential collisions:
This will help us understand if there are many EventIds generated in close proximity that might result in collisions when only the first 8 characters are used.
packages/ciphernode/logger/src/logger.rs (2)
3-3
: Importingerror
andinfo
macrosAdding
error
andinfo
from thetracing
crate is appropriate for enhanced logging functionality.
19-19
: Logging readiness message withinfo!
macroUsing
info!(node=%name, "READY!");
effectively logs the node's readiness state.packages/ciphernode/sortition/src/sortition.rs (1)
137-143
: Clarify error handling inGetHasNode
responseIn the
GetHasNode
handler, whenself.list.contains
returns anErr
, the error is sent to the bus, andfalse
is returned. This could lead to situations where the caller cannot distinguish between a node not being present and an error occurring during the check.Consider whether it's appropriate to return
false
on error, or if the error should be propagated or handled differently. If returningfalse
is intentional, ensure that the callers are aware thatfalse
may indicate an error, not just the absence of the node. You might want to document this behavior clearly.packages/ciphernode/p2p/src/libp2p_router.rs (3)
11-11
: Approved: Correctly importing necessary tracing macrosThe use of
tracing::{error, info, trace};
imports the necessary macros for structured logging.
97-97
: Approved: Logging default discovery type usinginfo!
Replacing
println!
withinfo!("Defaulting to MDNS discovery")
appropriately utilizes thetracing
crate for logging.
130-130
: Approved: Proper error logging when publishing failsLogging the error with
error!(error = ?e, "Error publishing line to swarm");
provides valuable debugging information.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (3)
- packages/ciphernode/logger/Cargo.toml (1 hunks)
- packages/ciphernode/p2p/src/p2p.rs (5 hunks)
- packages/ciphernode/sortition/src/sortition.rs (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/ciphernode/logger/Cargo.toml
- packages/ciphernode/p2p/src/p2p.rs
🧰 Additional context used
🔇 Additional comments (3)
packages/ciphernode/sortition/src/sortition.rs (3)
20-20
: LGTM: Improved error handling incontains
methodThe change to return
Result<bool>
instead ofbool
in thecontains
method signature enhances error handling capabilities, aligning with the PR objectives.
83-90
: LGTM: Improved event bus integrationThe addition of the
bus
field to theSortition
struct and the corresponding update to thenew()
constructor improve the structure for event handling. This change indirectly supports better logging capabilities.
95-95
: LGTM: Consistent event bus initializationThe update to the
attach
method ensures that the event bus is properly passed to theSortition
instance, maintaining consistency with the changes made to theSortition
struct and its constructor.
Closes: #124
println
withtracing::xxxx()
where apprpriateSummary by CodeRabbit
Release Notes
New Features
tracing
crate.Bug Fixes
Documentation
Tests